package com.exmaple.lemlin.rxjava;

import com.exmaple.lemlin.utils.ExceptionHandle;
import com.exmaple.lemlin.utils.JsonUtils;
import com.exmaple.lemlin.utils.LogUtils;

import java.util.Locale;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class RxSubscribe<T> implements Observer<T> {

    private Disposable disposable;

    @Override
    public void onSubscribe(Disposable d) {
        this.disposable = d;
        LogUtils.e("Start the subscribe");
    }

    @Override
    public void onNext(T t) {
        LogUtils.e(String.format(Locale.CANADA, "Respond data:%s%n",
                JsonUtils.objectToString(t)));
        try {
            onSuccess(t);
        } catch (Exception e) {
            e.printStackTrace();
            onHint("数据异常Exception:" + e.getMessage());
        }

    }

    @Override
    public void onError(Throwable e) {

        ExceptionHandle.ResponseThrowable error;
        if (e instanceof Exception) {
            error = ExceptionHandle.HandleException(e);
        } else {
            error = new ExceptionHandle.ResponseThrowable(e);
        }
        onHint(error.getMessage());
        LogUtils.e(String.format(Locale.CANADA, "Error code:%s%nError message:%s",
                error.getCode(), error.getMessage()));
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    public void onComplete() {
        LogUtils.e("End the subscribe");
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    public abstract void onSuccess(T t) throws Exception;

    public abstract void onHint(String hint);
}
